<?php

namespace App\Services;

use App\Models\OrderItem;
use App\Models\Product;
use App\Models\ProductVariant;

class OrderItemService
{
    /**
     * 创建订单项
     */
    public function createOrderItem(int $orderId, int $productId, ?int $variantId = null, int $quantity = 1, array $options = []): OrderItem
    {
        $product = Product::findOrFail($productId);
        $variant = $variantId ? ProductVariant::find($variantId) : null;

        // 验证变体是否属于该产品
        if ($variant && $variant->product_id !== $productId) {
            throw new \InvalidArgumentException('变体不属于该产品');
        }

        // 获取价格和SKU
        $price = $variant ? $variant->price : $product->price;
        $sku = $variant ? $variant->sku : $product->sku;

        // 构建规格信息
        $specifications = $this->buildSpecifications($product, $variant);

        // 计算小计金额
        $totalAmount = $price * $quantity;

        // 创建订单项
        $orderItem = OrderItem::create([
            'order_id' => $orderId,
            'product_id' => $productId,
            'variant_id' => $variantId,
            'sku' => $sku,
            'product_name' => $product->name,
            'variant_name' => $variant ? $variant->name : null,
            'specifications' => $specifications,
            'price' => $price,
            'quantity' => $quantity,
            'total_amount' => $totalAmount,
            'discount_amount' => $options['discount_amount'] ?? 0,
            'tax_amount' => $options['tax_amount'] ?? 0,
            'notes' => $options['notes'] ?? null,
            'status' => $options['status'] ?? 'pending',
        ]);

        return $orderItem;
    }

    /**
     * 构建规格信息
     */
    private function buildSpecifications(Product $product, ?ProductVariant $variant): array
    {
        if ($variant && $variant->attributes) {
            return $variant->attributes;
        }

        if ($product->specifications) {
            return $product->specifications;
        }

        return [];
    }

    /**
     * 从购物车创建订单项
     */
    public function createFromCart(int $orderId, array $cartItems): array
    {
        $orderItems = [];

        foreach ($cartItems as $cartItem) {
            $orderItem = $this->createOrderItem(
                $orderId,
                $cartItem['product_id'],
                $cartItem['variant_id'] ?? null,
                $cartItem['quantity'],
                [
                    'discount_amount' => $cartItem['discount_amount'] ?? 0,
                    'tax_amount' => $cartItem['tax_amount'] ?? 0,
                    'notes' => $cartItem['notes'] ?? null,
                ]
            );

            $orderItems[] = $orderItem;
        }

        return $orderItems;
    }

    /**
     * 更新订单项状态
     */
    public function updateStatus(OrderItem $orderItem, string $status): OrderItem
    {
        $orderItem->update(['status' => $status]);
        return $orderItem;
    }

    /**
     * 批量更新订单项状态
     */
    public function updateStatusBatch(array $orderItemIds, string $status): int
    {
        return OrderItem::whereIn('id', $orderItemIds)->update(['status' => $status]);
    }

    /**
     * 获取订单项详情
     */
    public function getOrderItemDetails(OrderItem $orderItem): array
    {
        return [
            'id' => $orderItem->id,
            'order_id' => $orderItem->order_id,
            'product_id' => $orderItem->product_id,
            'variant_id' => $orderItem->variant_id,
            'sku' => $orderItem->sku,
            'full_product_name' => $orderItem->full_product_name,
            'specifications' => $orderItem->specifications,
            'price' => $orderItem->price,
            'quantity' => $orderItem->quantity,
            'total_amount' => $orderItem->total_amount,
            'discount_amount' => $orderItem->discount_amount,
            'tax_amount' => $orderItem->tax_amount,
            'status' => $orderItem->status,
            'notes' => $orderItem->notes,
            'is_multi_variant' => $orderItem->isMultiVariant(),
            'is_single_variant' => $orderItem->isSingleVariant(),
            'created_at' => $orderItem->created_at,
            'updated_at' => $orderItem->updated_at,
        ];
    }

    /**
     * 验证库存
     */
    public function validateStock(int $productId, ?int $variantId = null, int $quantity = 1): bool
    {
        if ($variantId) {
            $variant = ProductVariant::find($variantId);
            return $variant && $variant->stock_quantity >= $quantity;
        }

        $product = Product::find($productId);
        return $product && $product->stock_quantity >= $quantity;
    }

    /**
     * 扣减库存
     */
    public function deductStock(OrderItem $orderItem): bool
    {
        if ($orderItem->isMultiVariant()) {
            $variant = $orderItem->variant;
            if ($variant && $variant->stock_quantity >= $orderItem->quantity) {
                $variant->decrement('stock_quantity', $orderItem->quantity);
                return true;
            }
        } else {
            $product = $orderItem->product;
            if ($product && $product->stock_quantity >= $orderItem->quantity) {
                $product->decrement('stock_quantity', $orderItem->quantity);
                return true;
            }
        }

        return false;
    }

    /**
     * 恢复库存
     */
    public function restoreStock(OrderItem $orderItem): bool
    {
        if ($orderItem->isMultiVariant()) {
            $variant = $orderItem->variant;
            if ($variant) {
                $variant->increment('stock_quantity', $orderItem->quantity);
                return true;
            }
        } else {
            $product = $orderItem->product;
            if ($product) {
                $product->increment('stock_quantity', $orderItem->quantity);
                return true;
            }
        }

        return false;
    }
}
